<template>
    <el-form-item
        label="兑奖方式"
        class="exchange_usage_type form-radio-item"
        :prop="`${props.rulePadStart}exchange_usage_type`">
        <el-radio-group v-model="formModel.exchange_usage_type" :disabled="edit">
            <el-radio :label="1">兑奖码</el-radio>
            <el-radio :label="2">线下邮寄</el-radio>
        </el-radio-group>
    </el-form-item>
    <div v-show="formModel.exchange_usage_type === 1">
        <el-form-item
            label="兑奖码"
            class="exchange_code_type form-radio-item"
            :prop="`${props.rulePadStart}exchange_code_type`">
            <el-radio-group v-model="formModel.exchange_code_type" :disabled="edit">
                <el-radio :label="1">系统自动生成</el-radio>
                <el-radio :label="2">导入兑换码</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item
            v-show="formModel.exchange_code_type === 2"
            label=""
            :prop="`${props.rulePadStart}exchange_file_list`"
            class="file-list">
            <!-- :limit="fileListLimit" -->
            <el-upload
                ref="upload"
                v-model:file-list="formModel.exchange_file_list"
                accept=".xlsx,.xls,.csv"
                :show-file-list="formModel.exchange_file_list?.length"
                :on-exceed="handleExceed"
                :before-upload="handBeforeUpload"
                :http-request="onHttpRequest">
                <el-button type="primary">
                    <span v-if="edit">
                        {{ formModel.exchange_file_list.length ? '追加文件' : '重新上传' }}
                    </span>
                    <span v-else>{{ formModel.exchange_file_list?.[0]?.code ? '追加文件' : '点击上传' }}</span>
                </el-button>
                <template #file="{ file }">
                    <div class="exchange-code-file-item" :class="{ 'file-code-status-del': file.type == 'new' }">
                        <el-icon class="file-code-icon"><Document /></el-icon>
                        <div class="file-code-name zw-text-ellipsis" @click="downExChangeCodeFile(file)">
                            {{ file.name || file.file_name }}
                        </div>
                        <div class="file-code-status">
                            <el-icon color="#60b900" size="14" class="success-icon">
                                <CircleCheck />
                            </el-icon>
                            <el-icon size="14" class="del-icon" @click="handleRemoveFile(file)">
                                <Delete />
                            </el-icon>
                        </div>
                        <div class="file-code-num">数量：{{ file.num ?? '...' }}</div>
                    </div>
                </template>
                <template #tip>
                    <div class="el-upload__tip">
                        导入兑奖码不能重复，文件不超过500kb；建议导入更多的备用兑奖码，以防回退后兑奖码失效
                    </div>
                </template>
            </el-upload>
            <el-button type="primary" link class="download_template" @click="downloadTemplate">下载模版</el-button>
        </el-form-item>
    </div>
    <div v-show="formModel.exchange_usage_type === 2">
        <el-form-item label="需填写邮寄信息" :prop="`${props.rulePadStart}mail_info`" class="form-radio-item">
            <el-checkbox-group v-model="formModel.mail_info">
                <el-checkbox v-for="item in mailInfoList" :key="item.system_code" :label="item">
                    {{ item.name }}
                </el-checkbox>
            </el-checkbox-group>
        </el-form-item>
        <el-form-item label="是否更新到客户上" :prop="`${props.rulePadStart}is_update`" class="form-switch-item">
            <el-switch v-model="formModel.is_update" :active-value="2" :inactive-value="1" />
            <span class="form-tip">姓名和邮寄地址会全部覆盖更新，手机号只会补充没有手机号的客户数据</span>
        </el-form-item>
    </div>
    <el-form-item label="兑奖期限" class="exchange_date exchange_item" :prop="`${props.rulePadStart}exchange_time`">
        <el-date-picker
            v-model="formModel.exchange_time"
            type="datetimerange"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="—"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime()"
            :disabled-date="disabledDataFun">
        </el-date-picker>
        <el-tooltip effect="dark" content="若未填写兑奖期限，则默认为永久有效" placement="top-start">
            <span class="exchange_date_label">
                <el-icon color="#ccc" size="16"><QuestionFilled /></el-icon>
            </span>
        </el-tooltip>
    </el-form-item>
    <el-form-item label="兑奖须知">
        <el-input
            v-model="formModel.exchange_desc"
            clearable
            show-word-limit
            placeholder="请保证获奖数据真实有效！"
            rows="3"
            type="textarea"
            maxlength="500"
            resize="none" />
    </el-form-item>
    <upload-fail-dialog v-model="dialogVisible" :data="dialogData" />
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue';
import {
    UploadInstance,
    UploadRawFile,
    UploadRequestOptions,
    ElMessage,
    UploadProps,
    genFileId,
    UploadFile
} from 'element-plus';
import uploadFailDialog from './upload-fail-dialog.vue';
import { defaultTime, downloadFile } from '@/utils/utils';
import { uploadFile2 } from '@/api/common';
import { importExChangeCode } from '@/api/smartMarketing/drainage/groupFission';
import { last } from 'lodash';

//
// 原来的版本是裂变引流使用，现在的1.0是群裂变使用。
// 不同点： 上传接口、库存的改变不删除文件、开通了线下邮寄等相关的功能
const props = withDefaults(defineProps<Props>(), {
    model: () => ({}),
    rulePadStart: '',
    basicDate: () => ({}),
    rewardList: () => [],
    fileListLimit: 1,
    edit: false
});

const formModel = computed(() => props.model);

/* ----------------------------兑换时间-start---------------------------- */
/** 时间禁用 */
const disabledDataFun = (time: any) => {
    if (props.basicDate.period_type === 2) {
        return time.getTime() < +new Date(props.basicDate?.activity_time?.[0]) - (8.64e7 - 1);
    }
    return time.getTime() < Date.now() - 8.64e7;
};
/* ----------------------------兑换时间-end---------------------------- */
/* ============================上传文件-start============================ */
const upload = ref<UploadInstance>();
const dialogVisible = ref<boolean>(false);
const dialogData = reactive<any[]>([]);

const handBeforeUpload = (rawFile: UploadRawFile) => {
    const type = ['xls', 'xlsx', 'csv'];
    const filetype = rawFile.name.split('.').pop() ?? '';
    if (!type.includes(filetype)) {
        ElMessage.warning('请上传xls、xlsx、或csv文件!');
        return false;
    }
    if (rawFile.size > 500 * 1024) {
        ElMessage.warning('文件大小不能超过500k!');
        return false;
    }
    return true;
};

// 超出时删除上一个
const handleExceed: UploadProps['onExceed'] = files => {
    clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    upload.value?.handleStart(file);
    upload.value?.submit();
};

// 自定义上传
const onHttpRequest = async (options: UploadRequestOptions) => {
    try {
        const lastFile: any = last(formModel.value.exchange_file_list);
        // 上传
        // 进度条
        const onUploadProgress = (progressEvent: any) => {
            // 后续要补充进度条和状态的交互
            lastFile.percentage = Math.floor((progressEvent.loaded * 100) / progressEvent.total);
        };
        const res = await uploadFile2(
            {
                file: options.file,
                fileName: options.file.name
            },
            { onUploadProgress }
        );
        // 给最后一个文件添加code
        lastFile.code = res.code;

        // 校验字段
        const params = {
            current: {
                id: formModel.value.id,
                code: res.code,
                // 有追加库存，优先使用追加的库存做判断
                stock_num: formModel.value.add_stock ?? formModel.value.reward_stock
            },
            codes: getFilterCodes(res.code)
        };
        const importRes = await importExChangeCode(params);
        if (importRes.success) {
            Object.assign(lastFile, {
                file_name: res.name,
                file_url: res.url,
                code: res.code,
                num: importRes.code_num,
                type: 'new'
            });
            return ElMessage.success('上传成功');
        }

        dialogVisible.value = true;
        dialogData.splice(0);
        dialogData.push(...importRes.err_lines);
        clearFiles();
    } catch {
        clearFiles();
    }
};
const clearFiles = () => {
    formModel.value.exchange_file_list.pop();
};

/** 删除文件 */
const handleRemoveFile = (file: UploadFile) => {
    upload.value?.handleRemove(file);
};

/** 过滤兑奖码文件的code */
const getFilterCodes = (code?: string) => {
    const codesCache: any = [];
    props.rewardList.forEach(item => {
        // 非实物奖励过绿
        if (item.reward_type !== 1) {
            return;
        }
        // 非兑换码类型过滤
        if (item.exchange_usage_type !== 1) {
            return;
        }

        // 非导入兑换码过滤
        if (item.exchange_code_type !== 2) {
            return;
        }

        // 过滤有兑换码的
        for (const rewardItem of item.exchange_file_list) {
            if (rewardItem.code) {
                codesCache.push({
                    id: item.id,
                    code: rewardItem.code,
                    stock_num: formModel.value.reward_stock
                });
            }
        }
    });
    const list = formModel.value.exchange_file_list.filter((el: any) => el.code != code);
    list.forEach((item: any) => {
        if (codesCache.every((el: any) => el.code != item.code)) {
            codesCache.push({
                id: item.id,
                code: item.code,
                stock_num: item.num
            });
        }
    });
    return codesCache;
};

// 下载模板默认地址
const downloadTemplate = () => {
    downloadFile(
        '//static.scrm.keyid.cn/keyid-scrm-server/template/%E5%85%91%E5%A5%96%E7%A0%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx'
    );
};

// 下载兑换码文件
const downExChangeCodeFile = (file: any) => {
    downloadFile(file.file_url);
};

/* ============================上传文件-end============================ */

/* ----------------------------线下邮寄兑奖-start---------------------------- */
const mailInfoList = reactive([
    { system_code: 'name', name: '姓名' },
    { system_code: 'mobile', name: '手机号' },
    { system_code: 'post_address', name: '邮寄地址' }
]);
// 兑奖方式切换时，如果未有选中的，则默认全部勾选上
watch(
    () => props.model.exchange_usage_type,
    () => {
        if (formModel.value.mail_info?.length) return;

        formModel.value.mail_info?.push(...mailInfoList);
    }
);
/* ----------------------------线下邮寄兑奖-end---------------------------- */

interface Props {
    /** 是否是编辑页面 */
    edit: boolean;
    model: object | any;
    /**奖品列表 */
    rewardList: Array<any>;
    // 校验的字符串名称的头部拼接字段名
    rulePadStart?: string;
    basicDate?: any;
    /** 上传的兑换码文件数量限制 */
    fileListLimit?: number;
}
</script>

<style lang="scss" scoped>
.el-form-item {
    margin-bottom: 24px;
}

.exchange_type,
.exchange_code_type {
    margin-bottom: 0px;
}

.exchange_type :deep(.el-form-item__error) {
    padding-top: 0;
    top: 26px;
}

.exchange_date {
    margin-top: 13px;
}

.exchange_item {
    margin-bottom: 22px !important;
}

.el-upload__tip {
    line-height: 14px;
    color: #969696;
    font-size: 12px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
}

:deep(.el-upload-list) {
    margin: 0;
    margin-top: 16px;

    .el-upload-list__item {
        margin-top: 8px;
        padding: 5px 12px;
        box-sizing: border-box;
        background-color: #f5f5f5;
        border-radius: 2px;
        line-height: normal;
        margin-bottom: 0;

        .el-upload-list__item-name {
            padding: 0;
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #585858;
        }

        .el-icon--close-tip {
            display: none !important;
        }

        .el-icon--close {
            right: 12px;
        }

        .el-upload-list__item-status-label {
            right: 12px;
        }

        &:hover {
            .el-icon--close {
                display: block !important;
            }
        }
    }
}

:deep(.el-progress__text) {
    min-width: 0;
    margin-left: 0px;
}

.download_template {
    position: absolute;
    top: 6px;
    left: 108px;
}
.exchange_date_label {
    display: inline-flex;
    margin-left: 8px;
    align-items: center;
    cursor: pointer;
    .el-icon {
        margin-right: 2px;
    }
}

:deep(.el-form-item) {
    margin-bottom: 0;
}

.file-list {
    margin-bottom: 24px;
}

// el-radio的formitem边距
.form-radio-item {
    margin-top: -8px;
    margin-bottom: 12px;
}
.el-form-item.form-switch-item {
    margin-top: -2px;
    margin-bottom: 18px !important;
}

:deep(.el-upload-list__item) {
    position: relative;
    padding: 8px;
    width: 430px;
    height: 32px;
    box-sizing: border-box;
    border-radius: 4px;
    background-color: #f7f7f7;
}

.exchange-code-file-item {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .file-code-icon {
        vertical-align: middle;
    }
    .file-code-name {
        cursor: pointer;
        margin-left: 4px;
        flex: 1;
    }
    .file-code-status {
        text-align: center;
        cursor: pointer;
        display: flex;
        align-items: center;

        .del-icon {
            display: none;
        }
        // &:hover:not(.edit) {
        //     .del-icon {
        //         display: inline-block;
        //         --color: '#ff6b00';
        //     }

        //     .success-icon {
        //         display: none;
        //     }
        // }
    }
    .file-code-num {
        position: absolute;
        width: max-content;
        top: 6px;
        left: 101%;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #666666;
    }
}
.file-code-status-del {
    &:hover:not(.edit) {
        .del-icon {
            display: inline-block;
            --color: '#ff6b00';
        }

        .success-icon {
            display: none;
        }
    }
}
// 表单中右侧的提示
.form-tip {
    flex: 1;
    margin-left: 6px;
    color: #999999;
    line-height: 18px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    line-height: 14px;
}

.file-list > :deep(.el-form-item__content) {
    margin-left: 140px;
}
</style>
